package com.pt25.base.dep.cassandra;


import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.HostDistance;
import com.datastax.driver.core.PoolingOptions;
import com.pt25.base.constants.BaseConstants;
import com.pt25.base.util.CollectionUtil;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
class CassandraConfig {
    @Resource
    private CassandraProperties cassandraProperties;

    @Bean("cassandraClusters")
    Map<String, Cluster> cassandraClusters() {
        Map<String, Cluster> cassandraClusterMap = new HashMap<>();
        if (null != cassandraProperties
                && CollectionUtil.isNotEmpty(cassandraProperties.getConfigs())
                && cassandraProperties.checkConfigs()) {
            cassandraProperties.getConfigs().forEach((config) -> {
                //连接池设置
                PoolingOptions poolingOptions = createPoolingOptions(config);
                String[] addresses = config.getContactPoints().split(",");
                Cluster cluster = Cluster.builder().addContactPoints(addresses)
                        .withPort(config.getPort())
                        .withCredentials(config.getUsername(), config.getPassword())
                        .withPoolingOptions(poolingOptions)
                        .build();
                cassandraClusterMap.put(config.getName(), cluster);
            });
            if (null != cassandraClusterMap.get(cassandraProperties.getPrimary())) {
                cassandraClusterMap.put(BaseConstants.DEFAULT, cassandraClusterMap.get(cassandraProperties.getPrimary()));
            }
        }
        return cassandraClusterMap;
    }


    private PoolingOptions createPoolingOptions(CassandraProperties.CassandraConfig cassandraConfig) {
        //连接池设置
        PoolingOptions poolingOptions = new PoolingOptions();
        // 每个连接的最大请求数
        poolingOptions.setMaxRequestsPerConnection(HostDistance.LOCAL, cassandraConfig.getLocalNewMaxRequests());
        // 表示和集群里的机器至少有2个连接 最多有4个连接
        poolingOptions.setCoreConnectionsPerHost(HostDistance.LOCAL, cassandraConfig.getLocalNewCoreConnections())
                .setMaxConnectionsPerHost(HostDistance.LOCAL, cassandraConfig.getLocalNewMaxConnections())
                .setCoreConnectionsPerHost(HostDistance.REMOTE, cassandraConfig.getRemoteNewCoreConnections())
                .setMaxConnectionsPerHost(HostDistance.REMOTE, cassandraConfig.getRemoteNewMaxConnections());
        return poolingOptions;
    }
}
